package songZhao.MinaDemo.SimpleDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
/**
 * 这个和server类大同小异,主要是结束部分,和链接等待部分.以及用户交互部分有所不同.
 * @author agui415
 *
 */
public class MinaClient {
	private NioSocketConnector connector = new NioSocketConnector();
	private DefaultIoFilterChainBuilder chainBuilder = connector.getFilterChain();
	private IoSessionConfig config = connector.getSessionConfig();
	private IoSession session;
	public void start(String host,int port) throws IOException {
		TextLineCodecFactory codecFactory = new TextLineCodecFactory(Charset.forName("UTF-8"),
				LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());
		ProtocolCodecFilter filter = new ProtocolCodecFilter(codecFactory);
		chainBuilder.addLast("codec_builder", filter);
		chainBuilder.addFirst("ClientFilter", new ClientFilter());
		
		config.setIdleTime(IdleStatus.BOTH_IDLE, 5);
		
		connector.setHandler(new ClientHandler());
		
		ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
		
		// 等待客户端链接完成
		connectFuture.awaitUninterruptibly();
		session = connectFuture.getSession();
		interact();
		/*
		 * interact方法结束后,说明已经向服务器发送了exit指令.
		 * 下边则需要等待服务器断开链接. 结束session
		 */
		session.getCloseFuture().awaitUninterruptibly();
		//session结束后,将connector清理掉,结束程序
		connector.dispose();
	}
	
	private void interact() throws IOException {
		/**
		 * 从标准输入中读取内容,并发送给客户端.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while (true) {
			line = reader.readLine();
			session.write(line);
			if (line.equals("exit")) {
				break;
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		MinaClient minaClient = new MinaClient();
		minaClient.start(args[0], Integer.parseInt(args[1]));
	}
}
